const logger = require('../logger');
const db = require('../../db');

class BusinessDetails {
    /**
     * 分类列表
     */
    getBusinessDetailsList(req) {
        logger.data.info('model.businessDetails.getBusinessDetailsList req：', req.params);
        return new Promise(function (resolve, reject) {
            // let condition = {};
            db.business_details.findAndCountAll({
                // attributes: [],
                // where: { isValid: 1 }, // 只取有效的分类
                order: [
                    ['update_time', 'desc']
                ],
            }).then(function (result) {
                resolve(result);
            }, function (err) {
                logger.error.error('model.businessDetails.getBusinessDetailsList error：', err);
                reject(err);
            });
        });
    }

    /**
     * 保存分类
     */
    saveBusinessDetails(req) {
        let reqData = req.body;
        let { businessId } = reqData;
        const now = new Date();
        // const uid = req.userInfo.uid;
        logger.data.info('model.businessDetails.saveBusinessDetails req：', reqData);
        return new Promise(function (resolve, reject) {
            reqData.update_time = now;
            // 修改
            if (businessId.toString()) {
                logger.data.info('model.businessDetails.saveBusinessDetails update：', reqData);
                db.business_details.update(reqData, {
                    where: { businessId }
                }).then(result => {
                    resolve(result[0]);
                }).catch(e => {
                    logger.error.error('model.businessDetails.saveBusinessDetails update error：', e);
                    resolve('');
                });
            } else {
                // 新增
                reqData.create_time = now;
                logger.data.info('model.businessDetails.saveBusinessDetails create：', reqData);
                db.business_details.create(reqData).then(result => {
                    resolve(result);
                }).catch(e => {
                    logger.error.error('model.businessDetails.saveBusinessDetails create error：', e);
                    resolve('');
                });
            }
        });
    }
}

module.exports = new BusinessDetails();
